import { app } from 'electron';
import path from 'node:path';
import { Conf } from 'electron-conf/main';
import { is } from '@electron-toolkit/utils';
import { UserSignProperties } from '#common/types/user';
import type { UserSettingsProperties, WorkflowSettingsProperties } from '#common/types/settings';
import { getMainWindow } from '$main/windows/main-window';
import { sendWebContentsEvent } from '$main/internal/event';

let userSignStore: Conf<UserSignProperties>;
let UserSettingStore: Conf<UserSettingsProperties>;
let WorkflowSettingStore: Conf<WorkflowSettingsProperties>;

export function getUserDataStore() {
  return userSignStore;
}

export function setupStore() {
  userSignStore = new Conf<UserSignProperties>({
    name: 'user-sign',
    dir: is.dev ? path.resolve(process.cwd()) : app.getPath('userData')
  });
  userSignStore.registerRendererListener();

  UserSettingStore = new Conf<UserSettingsProperties>({
    name: 'user-settings',
    dir: is.dev ? path.resolve(process.cwd()) : app.getPath('userData')
  });
  UserSettingStore.registerRendererListener();

  WorkflowSettingStore = new Conf<WorkflowSettingsProperties>({
    name: 'workflow-settings',
    dir: is.dev ? path.resolve(process.cwd()) : app.getPath('userData')
  });
  WorkflowSettingStore.registerRendererListener();

  WorkflowSettingStore.onDidChange('directory', (newVal) => {
    const mainWindow = getMainWindow();
    if (!mainWindow) return;

    sendWebContentsEvent(mainWindow.webContents, 'rc:workflow-settings-change', newVal);
  });
}
